<script>
export default {
  name: 'SelfSelect',
  props: {
    value: {
      type: [String, Array, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    options: {
      type: [Array, Function],
      default: () => []
    },
    optionParams: {
      type: Object,
      default: () => ({})
    },
    props: {
      type: Object,
      default: () => ({
        label: 'label',
        value: 'value'
      })
    },
    formatOptions: {
      type: Function,
      default: options => options
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      optionsList: [],
      loading: false
    }
  },
  computed: {
    selectValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('update:value', val)
      }
    },
    optionsAndParamsAndKey() {
      return {
        options: this.options,
        optionParams: this.optionParams
      }
    }
  },
  watch: {
    optionsAndParamsAndKey: {
      handler() {
        this.resetValueAndOptions()
        this.getOptions()
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.resetValueAndOptions()
    this.getOptions()
  },
  methods: {
    resetValueAndOptions() {
      this.selectValue = this.value || ''
      this.optionsList = []
    },
    getOptions() {
      if (typeof this.optionsAndParamsAndKey.options === 'function') {
        this.loading = true
        this.optionsAndParamsAndKey.options(this.optionsAndParamsAndKey.optionParams).then(res => {
          if (res.code === 200 && res.data) {
            this.formatOptions ? this.optionsList = this.formatOptions(res.data) : this.optionsList = res.data
          } else {
            this.optionsList = []
          }
        }).catch(() => {
          this.optionsList = []
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.optionsList = this.options
      }
    }
  }
}
</script>

<template>
  <el-select
    v-model="selectValue"
    v-loading="loading"
    :placeholder="placeholder"
    clearable
    filterable
    :multiple="multiple"
    collapse-tags
    :disabled="disabled"
  >
    <el-option
      v-for="item in optionsList"
      :key="item[props.value]"
      :label="item[props.label]"
      :value="item[props.value]"
    />
  </el-select>
</template>

<style scoped>

</style>
